package com.ruoyi.files.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.files.domain.SysFileInfo;
import com.ruoyi.files.service.ISysFileInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 文件信息Controller
 * 
 * @author ruoyi
 * @date 2024-11-14
 */
@Api(tags = "系统管理-文件信息")
@RestController
@RequestMapping("/files/files")
public class SysFileInfoController extends BaseController
{
    @Autowired
    private ISysFileInfoService sysFileInfoService;

    private static final String PYTHON_SCRIPT_PATH = "ruoyi-admin/src/main/resources/python/topUpDegree.py";
    //private static final String PYTHON_SCRIPT_PATH2 = "ruoyi-admin/src/main/resources/python/adultExamMatching.py";
    private static final String PYTHON_SCRIPT_PATH2 = "ruoyi-admin/src/main/resources/python/test.py";
    @ApiOperation("系统管理-文件信息 - AI智能识别填充数据")
    @PostMapping("/fillData")
    @ResponseBody
    //@PreAuthorize("@ss.hasPermi('files:files:list')")
    public Map<String, Object> getKeyValue(@RequestBody Map<Object,String> text) {
        System.out.println("this is fillData");
        System.out.println(text);
        String txt = text.get("txt");
        System.out.println(txt);



        Map<String, Object> entities = new HashMap<>();
        entities.put("text", txt);


        // 将Map转换为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        String jsonInput;
        try {
            jsonInput = mapper.writeValueAsString(entities);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        String jsonOutput = callPythonScript(PYTHON_SCRIPT_PATH, jsonInput);

        System.out.println("jsonOutput = " + jsonOutput);
        // 调用Python脚本并传递JSON字符串
        //String jsonOutput = callPythonScript(PYTHON_SCRIPT_PATH, jsonInput);

        // 将返回的JSON字符串转换回Map
        Map<String, Object> result;
        try {
            result = mapper.readValue(jsonOutput, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        System.out.println("result = " + result.toString());
        return result;

    }

    @ApiOperation("填充数据2")
    @PostMapping("/fillData2")
    @ResponseBody
    //@PreAuthorize("@ss.hasPermi('files:files:list')")
    public Map<String, Object> getKeyValue2(@RequestBody Map<Object,String> text) {
        System.out.println("this is fillData");
        System.out.println(text);
        String txt = text.get("txt");
        System.out.println(txt);



        Map<String, Object> entities = new HashMap<>();
        entities.put("text", txt);


        // 将Map转换为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
        String jsonInput;
        try {
            jsonInput = mapper.writeValueAsString(entities);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        String jsonOutput = callPythonScript(PYTHON_SCRIPT_PATH2, jsonInput);

        System.out.println("jsonOutput = " + jsonOutput);
        // 调用Python脚本并传递JSON字符串
        //String jsonOutput = callPythonScript(PYTHON_SCRIPT_PATH, jsonInput);

        // 将返回的JSON字符串转换回Map
        Map<String, Object> result;
        try {
            result = mapper.readValue(jsonOutput, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        System.out.println("result = " + result.toString());
        return result;

    }

    private String callPythonScript(String scriptPath, String jsonInput) {
        // 构建命令
        //List<String> commands = Arrays.asList("D:\\app\\anaconda\\envs\\sensevoice\\python.exe", scriptPath);

        // 使用ProcessBuilder执行Python脚本
        //ProcessBuilder processBuilder = new ProcessBuilder("D:\\Anaconda\\envs\\ljqenv\\python.exe",scriptPath,jsonInput);
//        ProcessBuilder processBuilder = new ProcessBuilder("D:\\app\\anaconda\\envs\\sensevoice\\python.exe",scriptPath,jsonInput);
        ProcessBuilder processBuilder = new ProcessBuilder("C:\\Users\\xiaosong\\.conda\\envs\\sensevoice\\python.exe",scriptPath,jsonInput);
        processBuilder.redirectErrorStream(true);
        //processBuilder.environment().forEach((key, value) -> System.out.println(key + " => " + value));

        processBuilder.environment().put("PYTHONIOENCODING", "UTF-8");
        try {
            Process process = processBuilder.start();


            // 读取Python脚本的标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            process.waitFor();

//            System.out.printf("output:"+output.toString());
            System.out.printf("output: %s%n", output.toString());

            // 仅返回最后的JSON输出
            String[] lines = output.toString().split("\n");
            for (String str : lines) {
                if (str.startsWith("{") && str.endsWith("}")) {
                    str = str.replace("'","\"");
                    return str;
                }
            }
            return null;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 查询文件信息列表
     */
    //@PreAuthorize("@ss.hasPermi('files:files:list')")
    @ApiOperation("文件信息管理 - 分页查询列表")
    @GetMapping("/list")
    public TableDataInfo list(SysFileInfo sysFileInfo)
    {
        startPage();
        List<SysFileInfo> list = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        return getDataTable(list);
    }

    /**
     * 导出文件信息列表
     */
    @PreAuthorize("@ss.hasPermi('files:files:export')")
    @Log(title = "文件信息", businessType = BusinessType.EXPORT)
    @ApiOperation("文件信息管理 - 导出数据")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFileInfo sysFileInfo)
    {
        List<SysFileInfo> list = sysFileInfoService.selectSysFileInfoList(sysFileInfo);
        ExcelUtil<SysFileInfo> util = new ExcelUtil<SysFileInfo>(SysFileInfo.class);
        util.exportExcel(response, list, "文件信息数据");
    }

    /**
     * 获取文件信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('files:files:query')")
    @GetMapping(value = "/{fileId}")
    @ApiOperation("文件信息管理 - 根据ID获取详细信息")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return success(sysFileInfoService.selectSysFileInfoByFileId(fileId));
    }

    /**
     * 新增文件信息
     */
//    @PreAuthorize("@ss.hasPermi('files:files:add')")
    @Log(title = "文件信息", businessType = BusinessType.INSERT)
    @ApiOperation("文件信息管理 - 新增数据")
    @PostMapping
    public AjaxResult add(@RequestBody SysFileInfo sysFileInfo)
    {
        return toAjax(sysFileInfoService.insertSysFileInfo(sysFileInfo));
    }

    /**
     * 修改文件信息
     */

    @PreAuthorize("@ss.hasPermi('files:files:edit')")
    @Log(title = "文件信息", businessType = BusinessType.UPDATE)
    @ApiOperation("文件信息管理 - 修改数据")
    @PutMapping
    public AjaxResult edit(@RequestBody SysFileInfo sysFileInfo)
    {
        return toAjax(sysFileInfoService.updateSysFileInfo(sysFileInfo));
    }

    /**
     * 删除文件信息
     */
    @PreAuthorize("@ss.hasPermi('files:files:remove')")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    @ApiOperation("文件信息管理 - 删除数据")
    public AjaxResult remove(@PathVariable Long[] fileIds)
    {
        return toAjax(sysFileInfoService.deleteSysFileInfoByFileIds(fileIds));
    }
}
